<template>
  <div class="purchaseRegionSeller">
    <el-form style="margin: 10px; margin-bottom: 0" :model="queryParams" ref="queryForm" size="small" inline>
      <el-row>
        <!-- 时间选择 -->
        <el-form-item>
          <el-date-picker
            v-model="queryParams.time"
            :start-placeholder="$t('开始时间')"
            :end-placeholder="$t('结束时间')"
            type="daterange"
            @change="getList"
            :clearable="false"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>

        <el-form-item prop="shopId">
          <el-select @change="getList" clearable v-model="queryParams.shopId" :placeholder="$t('店铺名称')">
            <el-option :label="item.name" :value="item.id" v-for="item in distributorShopList" />
          </el-select>
        </el-form-item>
      </el-row>
    </el-form>
    <div style="margin-left: 10px">
      包裹总数: <b>{{ totalNum }}</b>
    </div>
    <div id="charts"></div>

    <SellerSaleChart
      :show.sync="sellerSaleChart.show"
      :formData="sellerSaleChart.formData"
      :title="sellerSaleChart.title"
      :useThousand="sellerSaleChart.useThousand"
    >
      <div style="margin-left: 15px; font-size: 16px">
        地区: <b>{{ selectAreaName }}</b>
      </div>
    </SellerSaleChart>
  </div>
</template>

<script>
import { getDistributorShopList } from '@/api/statistics/skuSaleSeller'
import * as echarts from 'echarts'
import SellerSaleChart from '@/views/statistics/sellerSalePlatform/components/sellerSaleChart.vue'

import { getOrderAddressByDistrId } from '@/api/statistics/purchaseRegionSeller'
export default {
  activated() {
    this.$nextTick(() => this.$refs['TableRef']?.doLayout())
  },
  components: { SellerSaleChart },

  name: 'Index',
  data() {
    return {
      selectAreaName: '',
      sellerSaleChart: {
        show: false,
        useThousand: false,
        title: '',
        formData: {},
      },
      totalNum: '',
      type: 'earth',
      myChart: null,
      data: [],
      /**所有店铺 */
      distributorShopList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        spNo: '',
        skuNo: '',
        shopId: '',
        time: [],
      },
    }
  },
  computed: {},
  created() {
    this.queryParams.time = this.setStatisticsDefautTime('day')
    getDistributorShopList().then((res) => {
      this.distributorShopList = res.data
    })
  },
  mounted() {
    fetch(`/japan.geojson`)
      .then((version) => version.json())
      .then((res) => {
        this.myChart = echarts.init(document.getElementById('charts'))
        this.myChart.hideLoading()
        echarts.registerMap('japan', res, {
          ['沖縄県']: {
            // 把沖縄県左下方
            left: 120,
            top: 32,
            width: 2,
          }, // 新的坐标
        })

        window.addEventListener('resize', () => this.myChart.resize())
        this.myChart.on('click', (params) => {
          if (params.componentType === 'series' && params.seriesType === 'bar') {
            this.selectAreaName = params.name
            this.sellerSaleChart.formData = {
              type: 3,
              time: this.queryParams.time,
              shopId: this.queryParams.shopId || 'null',
              address1: params.name,
              distrId: JSON.parse(localStorage.getItem('distr') || '{}').distrId,
            }
            this.sellerSaleChart.title = params.name
            this.sellerSaleChart.show = true
          }
        })
        this.myChart.on('mouseover', (params) => {
          // if (params.seriesType === 'bar') {
          // 使用 dispatchAction 触发对应的区域高亮
          this.myChart.dispatchAction({
            type: 'highlight',
            name: params.name,
          })
          // }
        })

        this.myChart.on('mouseout', (params) => {
          // if (params.seriesType === 'bar') {
          // 使用 dispatchAction 取消对应的区域高亮
          this.myChart.dispatchAction({
            type: 'downplay',
          })
          // }
        })
        this.getList()
      })
  },
  methods: {
    generateColors() {
      function generateColors(numColors, startColor, endColor) {
        const start = hexToRgb(startColor)
        const end = hexToRgb(endColor)

        const colors = []

        for (let i = 0; i < numColors; i++) {
          const ratio = i / (numColors - 1)
          const red = Math.round(start.r + (end.r - start.r) * ratio)
          const green = Math.round(start.g + (end.g - start.g) * ratio)
          const blue = Math.round(start.b + (end.b - start.b) * ratio)

          colors.push(rgbToHex(red, green, blue))
        }

        return colors
      }

      function hexToRgb(hex) {
        const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
        return result
          ? {
              r: parseInt(result[1], 16),
              g: parseInt(result[2], 16),
              b: parseInt(result[3], 16),
            }
          : null
      }

      function rgbToHex(r, g, b) {
        return '#' + componentToHex(r) + componentToHex(g) + componentToHex(b)
      }

      function componentToHex(c) {
        const hex = c.toString(16)
        return hex.length === 1 ? '0' + hex : hex
      }
      const colors = generateColors(47, '#a50026', '#faf0f2')
      return colors.reverse()
    },
    handleSwitch() {
      this.drawEcharts()
    },
    getList() {
      /****************** 处理查询条件 *********************/
      const selectDate = this.queryParams.time || []
      const startTime = selectDate[0] || ''
      const endTime = selectDate[1] || ''
      const data = {
        ...this.queryParams,
        startTime,
        endTime,
      }
      delete data.time
      /**************** 处理查询条件 end *******************/
      getOrderAddressByDistrId(data).then((res) => {
        this.data = res.data
        let total = 0
        res.data.map((i) => {
          total += +i.value || 0
        })
        this.totalNum = total
        this.drawEcharts()
      })
    },
    /** 初始化图表 */
    drawEcharts() {
      if (this.data.length == 0) {
        return this.myChart.setOption({})
      }
      const data = this.data.sort((a, b) => +b.value - +a.value)
      const arr = this.data.map((i) => +i.value).sort((a, b) => b - a)
      const max = arr[0]
      const min = 0
      const color = this.generateColors()
      let option
      option = {
        title: {
          left: 'center',
          text: '销售地区统计(S)',
          textStyle: {
            fontSize: '25px',
          },
        },

        tooltip: {
          formatter: ({ seriesType, name, value }) => {
            if (seriesType == 'map') {
              return name + ': ' + value
            }
            if (seriesType == 'bar') {
              return name + ': ' + value
            }
          },
        },
        grid: {
          top: '42px',
          bottom: '40px',
          right: '40px',
          left: '90px',
        },
        xAxis: {
          type: 'value',
        },
        yAxis: {
          type: 'category',
          axisLabel: {
            // rotate: 30,
            interval: 0,
            fontSize: 11,
          },
          data: data.reverse().map((i) => i.name),
        },
        visualMap: {
          left: 'right',
          bottom: '50px',
          max,
          min,
          inRange: {
            color,
          },
          // text: [`最大值${max}`, `最小值${min}`],
          calculable: true,
        },
        series: [
          {
            type: 'bar',
            id: 'population',
            data: data.map((i, index) => {
              return {
                ...i,
                itemStyle: {
                  color: color[index],
                },
              }
            }),
            universalTransition: true,
            itemStyle: {
              // 设置高亮状态下的颜色
              emphasis: {
                color: '#ffde33',
              },
            },
          },
          {
            // 地图数据
            type: 'map',
            map: 'japan',
            data: this.data.map(({ name, value }) => {
              return {
                name,
                value,
              }
            }),
          },
        ],
      }

      this.myChart.setOption(option)
    },
  },
}
</script>

<style scoped lang="scss">
.purchaseRegionSeller {
  width: 100%;
  display: flex;
  flex-direction: column;
  min-height: calc(100vh - 84px);

  #charts {
    width: 100%;
    flex: 1;
  }
}
</style>
